#!/bin/ksh
#
# runsedflux-test - run a series of sedflux suite
#
# usage:
#
# runsedflux-test test_dir [test_name_1 test_name_2 ...]
#
# test_dir       - the directory to run the test(s) in.
# test_name      - the name of the test to run.
#

copy_sedflux_test_files () {
   init_file=$2_init.kvf
   epoch_file=$2_epoch.kvf
   test_file_dir=$SEDFLUX_SHARE

   input_files=bench_river.kvf
   hydro_file=bench_river.kvf
   sediment_file=bench_sediment.kvf
   bathy_file=bench_bathy.csv
   input_file=bench_input_be.seq
   current_file=bimodal_current.csv

   test_dir=$1/$2

   mkdir -p $1
   mkdir -p $1/$2

   $CP $test_file_dir/$hydro_file $test_dir
   $CP $test_file_dir/$sediment_file $test_dir
   $CP $test_file_dir/$bathy_file $test_dir
   $CP $test_file_dir/$input_file $test_dir
   $CP $test_file_dir/$current_file $test_dir

   $CP $test_file_dir/$init_file $test_dir
   $CP $test_file_dir/$epoch_file $test_dir
}

trap_handler () {
   print 'Exiting sedflux batch run...'
   exit 1
}

run_sedflux_test () {
   test_dir=$1/$2
   test_name=$2

   init_file=${test_name}_init.kvf

   print "Running test: $test_name"
   cd $test_dir && $SEDFLUX_HOME/bin/sedflux -3 --msg=$init_file --init-file=$init_file > output.txt 2> /dev/null
   print "Finished test: $test_name"
}

check_input_args () {

   if [[ ! -a $1 ]]
   then
      print "$1: unable to find batch directory."
      return 1
   fi

   if [[ ! -a $2 ]]
   then
      if ! touch $2
      then
         print "$2: unable to create input file."
         return 1
      else
         rm -f $2
      fi
   else
      if [[ ! -r $2 && ! -w $2 ]]
      then
         print "$2: you do not have read and write permission for input file."
         return 1
      fi
   fi
      
   if [[ ! -a $3 ]]
   then
      if ! touch $3
      then
         print "$3: unable to create output file."
         return 1
      else
         rm -f $3
      fi
   else
      if [[ ! -w $3 ]]
      then
         print "$3: you do not have write permission for output file."
         return 1
      fi
   fi
         
   if ! touch $TMPDIR
   then
      print "$TMPDIR: can not create temporary directory."
      exit 1
   fi

}


LS=/bin/ls
RM=/bin/rm
MV=/bin/mv
CP=/bin/cp
PWD=/bin/pwd

SEDFLUX_DIR=@prefix@
SEDFLUX_HOME=$SEDFLUX_DIR
SEDFLUX_SHARE=$SEDFLUX_DIR/share/sedflux
ALL_TESTS="avulsion bbl compaction plume_0 plume_1 plume_2 plume_3 river storm"

export SEDFLUX_DIR
export SEDFLUX_HOME
export SEDFLUX_SHARE

TMPDIR=/tmp/sedflux_tests

###
### Read the command line parameters.
###

TEST_DIR=`pwd $1`

shift 1
TEST_NAME=$@

if [[ $# -eq 0 ]]
then
   TEST_NAME=$ALL_TESTS
fi
#check_input_args $1 $2 || exit 1

###
### Create a separate directory for each test.
###
for t in $TEST_NAME
do
   copy_sedflux_test_files $TEST_DIR $t
done

###
### Run the test
###
for t in $TEST_NAME
do
   run_sedflux_test $TEST_DIR $t &
done

wait



